import re

from django_redis import get_redis_connection
from rest_framework import serializers

from goods.models import SKU
from users.constants import USER_BROWSING_HISTORY_COUNTS_LIMIT
from users.models import User, Address
from users.utils import decode_accesstoken, generate_find_password_accesstoken


class UserSerializer(serializers.ModelSerializer):
    """用户序列化器类"""
    password2 = serializers.CharField(label='重复密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)
    token = serializers.CharField(label='JWT token', read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'mobile', 'password2', 'sms_code', 'allow', 'token')

        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    # 是否同意协议，手机号格式，手机号是否存在，两次密码是否一致，短信验证码是否正确
    # 额外验证

    def validate_username(self, value):
        # 用户名不能全部为数字
        if re.match(r'^\d+$', value):
            raise serializers.ValidationError('用户名不能全部为数字')

        return value

    # 是否同意协议
    def validate_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError('请同意协议')

        return value

    # 手机号格式是否正确
    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式不正确')

        # 手机号是否存在
        count = User.objects.filter(mobile=value).count()
        if count > 0:
            raise serializers.ValidationError('手机号已存在')

        return value

    # 两次密码是否一致
    def validate(self, attrs):
        password = attrs['password']
        password2 = attrs['password2']

        if password != password2:
            raise serializers.ValidationError('两次密码不一致')
        # 短信验证码是否正确
        mobile = attrs['mobile']

        # 从redis中获取真实的短信验证码
        redis_conn = get_redis_connection('verify_codes')

        real_sms_code = redis_conn.get('sms_%s' %mobile) # bytes

        if real_sms_code is None:
            raise serializers.ValidationError('短信验证码已失效')

        # 对比验证码的内容
        sms_code = attrs['sms_code'] # str

        if real_sms_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码错误')

        return attrs

    def create(self, validated_data):
        """validated_data:校验之后的数据"""
        # 清除无用的数据
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        # 创建新用户并保存到数据库
        user = User.objects.create_user(**validated_data)

        # 由服务器生成一个jwt token，保存用户身份信息
        from rest_framework_jwt.settings import api_settings

        # 生成payload的方法
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER

        # 生成jwt token的方法
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        # 生成payload
        payload = jwt_payload_handler(user)
        # 生成jwt token
        token = jwt_encode_handler(payload)

        # 给user对象增加token属性，保存jwt token的数据
        user.token = token

        return user


class UserDetailSerializer(serializers.ModelSerializer):
    """用户序列化器类"""
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


# class EmailSerializer(serializers.ModelSerializer):
#     """邮箱序列化器类"""
#     class Meta:
#         model = User
#         fields = ('id', 'email')
#
#         extra_kwargs = {
#             'email': {
#                 'required': True
#             }
#         }
#
#     def update(self, instance, validated_data):
#         # 设置用户登录的邮箱
#         email = validated_data['email']
#         instance.email = email
#         instance.save()
#
#         # TODO: 给邮箱发送验证邮件
#
#         return instance


class EmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'email')

        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    def update(self, instance, validated_data):
        # 设置用户登录的邮箱
        email = validated_data['email']
        instance.email = email
        instance.save()

        # TODO: 给邮箱发送验证邮件
        # itsdangerous
        # 验证链接： http://www.meiduo.site:8080/success_verify_email.html?user_id=<用户id>
        # 如果直接将用户的id放在验证链接中，可能会发生恶意请求
        # 将用户的信息进行加密，然后把加密之后的内容放在验证链接中
        # http://www.meiduo.site:8080/success_verify_email.html?token=<加密用户之后的信息>
        verify_url = instance.generate_verify_email_url()

        # 发出发送邮件的任务消息
        # 发出发送邮件的任务消息
        from celery_tasks.email.tasks import send_verify_email
        send_verify_email.delay(email, verify_url)

        return instance


class AddressSerializer(serializers.ModelSerializer):
    """地址序列化器类"""
    province_id = serializers.IntegerField(label='省')
    city_id = serializers.IntegerField(label='市')
    district_id = serializers.IntegerField(label='区')
    province = serializers.StringRelatedField(read_only=True, label='省名称')
    city = serializers.StringRelatedField(read_only=True, label='市名称')
    district = serializers.StringRelatedField(read_only=True, label='区县名称')

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate_mobile(self, value):
        # 手机号格式验证
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')

        return value

    def create(self, validated_data):
        # 创建并保存新增地址数据
        # 获取user对象
        user = self.context['request'].user
        validated_data['user'] = user

        # 调用ModelSerializer中的create方法，创建对象
        addr = super().create(validated_data)

        return addr


class TitleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address
        fields = ('id', 'title')


class BrowseHistoriesSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(label='SKU商品编号')

    def validated_sku_id(self, value):
        try:
            sku = SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        return value

    def create(self, validated_data):
        # 1.去重lrem
        # 1.1 获取redis连接
        redis_conn = get_redis_connection('histories')
        # 1.2 拼接redis的key
        user = self.context['request'].user
        redis_key = 'history_%s' % user.id
        sku_id = validated_data['sku_id']
        # 1.3 去重
        redis_conn.lrem(redis_key, 0, sku_id)

        # 2.有序lpush
        redis_conn.lpush(redis_key, sku_id)

        # 3.截取ltrim
        redis_conn.ltrim(redis_key, 0, USER_BROWSING_HISTORY_COUNTS_LIMIT - 1)

        return validated_data


class VerifySmscodeSerializer(serializers.Serializer):
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    user_id = serializers.IntegerField(label='用户编号', read_only=True)
    username = serializers.CharField(min_length=5, max_length=20, write_only=True)
    access_token = serializers.CharField(label='accress_token', read_only=True)

    def validate(self, attrs):
        sms_code = attrs['sms_code']
        username = attrs['username']
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExit:
            raise serializers.ValidationError("用户名有误")

        sms_code_redis_key = "sms_%s" % user.mobile

        redis_conn = get_redis_connection('verify_codes')
        sms_code_redis = redis_conn.get(sms_code_redis_key)

        if not sms_code_redis:
            raise serializers.ValidationError("短信验证码已过期")

        # 比较手机验证码是否正确
        if sms_code_redis.decode() != sms_code:
            raise serializers.ValidationError("短信验证码输入有误")

        return attrs

    def create(self, validated_data):

        # 组织响应数据返回{"user_id": "", "access_token": ""}
        username = validated_data['username']
        user = User.objects.get(username=username)

        access_token = generate_find_password_accesstoken(username)

        # 给validated_data添加属性access_token
        validated_data['access_token'] = access_token
        validated_data['user_id'] = user.id

        return validated_data


class SavePasswordSerializer(serializers.Serializer):

    password = serializers.CharField(label='新密码', write_only=True, min_length=8, max_length=20,)
    password2 = serializers.CharField(label='新密码重复', write_only=True, min_length=8, max_length=20,)
    access_token = serializers.CharField(label='access_token', write_only=True)
    pk = serializers.IntegerField(label='用户id', write_only=True)

    def validate(self, attrs):
        password = attrs['password']
        password2 = attrs['password2']
        access_token = attrs['access_token']
        pk = attrs['pk']

        # 检验两次密码是否一致
        if password != password2:
            raise serializers.ValidationError("两次输入密码不一致")

        # access_token 解密校验
        username_dict = decode_accesstoken(access_token)
        # 为空校验
        if not username_dict:
            raise serializers.ValidationError("access_token不正确")

        # 正确校验
        username = username_dict['secret_key']
        if not username:
            raise serializers.ValidationError("access_token不正确")
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            raise serializers.ValidationError("access_token不正确")

        try:
            user2 = User.objects.get(id=pk)
        except User.DoesNotExist:
            raise serializers.ValidationError("用户id有误")

        if user2.id != user.id:
            raise serializers.ValidationError('操作用户不一致')

        return attrs

    def update(self, instance, validated_data):

        password = validated_data['password']

        instance.set_password(password)

        instance.save()

        return instance


class UpdatePasswordSerializer(serializers.Serializer):
    """修改密码序列化器类"""
    user_id = serializers.CharField(label='用户id', write_only=True)
    old_password = serializers.CharField(label='当前密码', max_length=20)
    password = serializers.CharField(label='新密码', max_length=20)
    password2 = serializers.CharField(label='用于判断新密码', max_length=20)

    def validate(self, attrs):
        # user_id = attrs['user_id']
        user_id = attrs['user_id']
        old_password = attrs['old_password']
        password = attrs['password']
        password2 = attrs['password2']

        user = self.context['user']
        # user_id = user.id
        #
        # try:
        #     user = User.objects.filter(id=user_id)[0]
        # except User.DoesNotExist:
        #     raise serializers.ValidationError('用户不存在')

        if int(user_id) != int(user.id):
            raise serializers.ValidationError('用户id不匹配')

        if not user.check_password(old_password):
            raise serializers.ValidationError('原密码输入错误')

        if password != password2:
            raise serializers.ValidationError('两次密码不一致')

        return attrs

    # def update(self, instance, validated_data):
    #
    #     user = self.context['request'].user
    #
    #     user.set_password(validated_data['password'])
    #
    #     user.save()
    #
    #     return user

    def create(self, validated_data):

        user = self.context['user']

        user.set_password(validated_data['password'])

        user.save()

        return user

